<template>
  <div>
    <div class="ml-2 flex-1">
      <div>
        <a-card :bordered="false" style="height: 830px; width: 1380px">
          <a-form layout="inline" :model="searchForm" ref="searchFormRef">
            <a-form-item label="收费期" name="year">
              <a-date-picker v-model:value="searchForm.year" picker="year" />
            </a-form-item>
            <a-form-item label="停供状态" name="state">
              <a-select v-model:value="searchForm.state" :options="stateOptions" allow-clear placeholder="请选择停供状态"
                style="width: 150px" />
            </a-form-item>
            <a-form-item label="停供方式" name="stopType">
              <a-select v-model:value="searchForm.stopType" :options="stopTypeOptions" allow-clear placeholder="请选择停供方式"
                style="width: 150px" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(SearchOutlined)" @click="onSearch">
                查询
              </a-button>
              <a-button type="primary" style="margin-left: 10px" :icon="h(ReloadOutlined)" @click="onReset">
                重置
              </a-button>
              <a-button type="primary" style="margin-left: 10px">特殊停供</a-button>
              <a-button type="primary" style="margin-left: 10px" @click="batchExport">批量导出开关栓状态</a-button>
              <a-button type="primary" style="margin-left: 10px" @click="
                () => {
                  isHistory = true;
                  getHistory();
                }
              " :icon="h(HistoryOutlined)">导出历史</a-button>
              <a-button type="primary" style="margin-left: 10px" @click="batchImport">批量导入开关栓状态</a-button>
            </a-form-item>
          </a-form>
          <a-table :columns="columns" :data-source="dataSource" bordered :pagination="pagination" class="mt-5"
            :row-class-name="(_record: any, index: number) =>
                index % 2 === 1 ? 'table-striped' : null
              " :scroll="{ x: 1700, y: 550 }">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" @click="print(record)">打印停供单</a-button>
                <a-button type="link" @click="recover(record)">恢复供热</a-button>
                <a-popconfirm title="确定要删除这条数据吗？" ok-text="确定" cancel-text="取消" @confirm="confirm" @cancel="cancel"
                  placement="bottom">
                  <a-button type="link" danger>删除</a-button>
                </a-popconfirm>
              </template>
            </template>
          </a-table>
        </a-card>
      </div>
    </div>
    <a-modal v-model:open="isHistory" title="导出历史" :footer="null" width="1200px">
      <a-table :columns="historyColumns" :data-source="historyDataSource" bordered :pagination="historyPagination"
        class="mt-3" :row-class-name="(_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
          ">
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'">完成</a-tag>
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { reactive, h, ref } from 'vue';
import { useRouter } from 'vue-router';
import {
  SearchOutlined,
  ReloadOutlined,
  HistoryOutlined,
} from '@ant-design/icons-vue';
import {
  getValveManagementApi,
  getValveManagementRecoverApi,
  getValveManagementBatchExportApi,
  getValveManagementBatchExportHistoryApi,
} from '#/api/core/valveManagement';
import { message } from 'ant-design-vue';
// import { getStopApi } from "#/api/valveManagement";
import dayjs from "dayjs";

const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const searchFormRef = ref(null);
const isHistory = ref(false);
const searchForm = reactive({
  year: '',
  state: undefined,
  stopType: undefined,
});
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'operationDate',
    key: 'operationDate',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'states',
    key: 'states',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const historyDataSource = ref([]);
const columns = [
  {
    title: '用户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户名称',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '面积名称',
    dataIndex: 'areaName',
    key: 'areaName',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
    align: 'center',
  },
  {
    title: '停供开始时间',
    dataIndex: 'heatingStartDate',
    key: 'heatingStartDate',
    align: 'center',
  },
  {
    title: '停供结束时间',
    dataIndex: 'heatingEndDate',
    key: 'heatingEndDate',
    align: 'center',
  },
  {
    title: '附件',
    dataIndex: 'fileList',
    key: 'fileList',
    align: 'center',
    fixed: 'right',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    fixed: 'right',
    width: 300,
  },
];
const dataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    getHistory();
  },
});
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  } else {
    const query = {
      page: pagination.current,
      limit: pagination.pageSize,
      year: '',
      stopWay: '',
      heatingStatus: '',
      treeData: props.selectedNodeId,
    };
    getValveManagementApi(query).then((res: any) => {
      console.log(res);
      dataSource.value = res.data;
      pagination.total = res.total;
    });
  }

};
const recover = (record: any) => {
  const query = {
    areaID: record.areaID,
    year: record.year,
  };
  getValveManagementRecoverApi(query).then((res: any) => {
    console.log(res);
  });
};
const batchExport = () => {
  getValveManagementBatchExportApi(props.selectedNodeId.join(',')).then(
    (res: any) => {
      console.log(res);
      if (res.data.data.code == 200) {
        message.success(res.data.data.data);
      } else {
        message.error('导出失败');
      }
    },
  );
};
const batchImport = () => {
  // 路由跳转到/valveManagement/batchImport
  useRouter().replace('/valveManagement/batchImport');
};
const getHistory = () => {
  getValveManagementBatchExportHistoryApi(
    historyPagination.current,
    historyPagination.pageSize,
    5,
  ).then((res: any) => {
    console.log(res);
    historyDataSource.value = res.data.data.data;
    historyPagination.total = res.data.data.total;
  });
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
</script>
<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
